# 评论的视图函数
# # get_object_or_404()：它和Model.objects.get()的功能基本是相同的。
# 区别是在生产环境下，如果用户请求一个不存在的对象时，Model.objects.get()会返回Error 500（服务器内部错误），
# 而get_object_or_404()会返回Error 404。相比之下，返回404错误更加的准确。
# redirect()：返回到一个适当的url中：即用户发送评论后，重新定向到文章详情页面。
# 当其参数是一个Model对象时，会自动调用这个Model对象的get_absolute_url()方法
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,JsonResponse
from django.urls import reverse

from article.models import ArticlePost
from .forms import CommentForm
from .models import Comment,Notification
from django.views.generic import ListView

# 文章评论
@login_required(login_url='/accounts/login/')
def post_comment(request, article_id, parent_comment_id=None):
    article = get_object_or_404(ArticlePost, id=article_id)

    # 处理 POST 请求
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.article = article
            new_comment.user = request.user
                        # 二级回复
            if parent_comment_id:
                parent_comment = Comment.objects.get(id=parent_comment_id)
                # 若回复层级超过二级，则转换为二级
                new_comment.parent_id = parent_comment.get_root().id
                # 被回复人
                new_comment.reply_to = parent_comment.user
            new_comment.save()
            # 发送通知给被评论的用户
            if new_comment.user != new_comment.article.author:  # 防止作者收到自己的通知
                notify = Notification(
                    recipient=new_comment.article.author,
                    actor=request.user,
                    verb='评论了你的文章',
                    target=new_comment.article,
                    action_object=new_comment
                )
                notify.save()
            # 判断是否是 ajax 请求
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return HttpResponse('200 OK')
            return redirect(article)
        else:
            return HttpResponse("表单内容有误，请重新填写。")
        # 处理 GET 请求
    elif request.method == 'GET':
        comment_form = CommentForm()
        context = {
            'comment_form': comment_form,
            'article_id': article_id,
            'parent_comment_id': parent_comment_id
        }
        return render(request, 'comment/reply.html', context)
    
    # 处理错误请求
    else:
        return HttpResponse("发表评论仅接受POST请求。")
    
# 删除评论
@login_required(login_url='/accounts/login/')
def delete_comment(request, comment_id):
    if request.method == 'POST':
        comment = get_object_or_404(Comment, id=comment_id)
        # 验证用户权限
        if request.user != comment.user and not request.user.is_superuser:
            return HttpResponse("你没有权限删除这条评论")
        
        # 获取文章 id，用于重定向
        article_id = comment.article.id
        comment.delete()
        return redirect("article:article_detail", id=article_id)
    else:
        return HttpResponse("仅允许post请求")
    
#显示用户的通知，类视图    
class NotificationListView(ListView):
    model = Notification
    template_name = 'comment/notification_list.html'
    context_object_name = 'notifications'

    def get_queryset(self):
         # 将所有未读通知标记为已读
        Notification.objects.filter(recipient=self.request.user, is_read=False).update(is_read=True)
        return Notification.objects.filter(recipient=self.request.user).order_by('-created_at')